package v1

import (
	"github.com/gin-gonic/gin"
	"go-admin/global"
	mr "go-admin/internal/model/api/model_request"
	ms "go-admin/internal/model/api/model_response"
	"go-admin/internal/service"
	"go-admin/pkg/app"
	"go-admin/pkg/errcode"
)

type Dept struct{}

func NewDept() *Dept {
	return &Dept{}
}

func (d *Dept) Create(c *gin.Context) {
	param := mr.CreateDeptRequest{}
	response := app.NewResponse(c)
	valid, errors := app.BindAndValid(c, &param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errors)
		response.Fail(app.WithMsg(errors.Errors()...))
		return
	}
	svc := service.New(c.Request.Context())
	insertId, err := svc.CreateDept(&param)
	if err != nil {
		global.Logger.WithCaller(2).Errorf("svc.CreateDept err: %v", err)
		response.Fail(app.WithMsg(errcode.ErrCreate))
		return
	}
	response.Ok(app.WithData(app.ToId(insertId)))
	return
}

func (d *Dept) Update(c *gin.Context) {
	param := mr.UpdateDeptRequest{}
	response := app.NewResponse(c)
	valid, errors := app.BindAndValid(c, &param)
	if !valid {
		// 打印日志
		global.Logger.Errorf("app.BindAndValid errs: %v", errors)
		response.Fail(app.WithMsg(errors.Errors()...))
		return
	}
	svc := service.New(c.Request.Context())
	if err := svc.UpdateDept(&param); err != nil {
		global.Logger.WithCaller(2).Errorf("svc.UpdateDept err: %v", err)
		response.Fail(app.WithMsg(errcode.ErrEdit))
		return
	}
	response.Ok()
	return
}

// 删除
func (d *Dept) Delete(c *gin.Context) {
	param := mr.CommonId{Id: c.Param("id")}
	response := app.NewResponse(c)
	valid, errors := app.BindAndValid(c, &param)
	if !valid {
		// 打印日志
		global.Logger.Errorf("app.BindAndValid errs: %v", errors)
		response.Fail(app.WithMsg(errors.Errors()...))
		return
	}
	svc := service.New(c.Request.Context())
	if err := svc.DeleteDept(param.Id); err != nil {
		// 打印日志
		global.Logger.WithCaller(2).Errorf("svc.DeleteDict errs: %v", errors)
		response.Fail(app.WithMsg(err.Error()))
		return
	}
	response.Ok()
	return
}

// 获取tree
func (d *Dept) GetDeptTree(c *gin.Context) {
	response := app.NewResponse(c)
	svc := service.New(c.Request.Context())
	deptTree, err := svc.GetDeptTree()
	if err != nil {
		// 打印日志
		global.Logger.Errorf("svc.CountDict errs: %v", err)
		response.Fail(app.WithMsg(err.Error()))
		return
	}
	response.Ok(app.WithData(app.ToList(deptTree)))
	return
}

func (d *Dept) DeptDetailById(c *gin.Context) {
	param := mr.CommonId{}
	response := app.NewResponse(c)
	valid, errors := app.BindAndValid(c, &param)
	if !valid {
		// 打印日志
		global.Logger.Errorf("app.BindAndValid errs: %v", errors)
		response.Fail(app.WithMsg(errors.Errors()...))
		return
	}
	svc := service.New(c.Request.Context())
	dept, err := svc.GetDeptById(param.Id)
	if err != nil {
		// 打印日志
		global.Logger.WithCaller(2).Errorf("app.GetDeptById errs: %v", err)
		response.Fail(app.WithMsg(errcode.ErrGet))
		return
	}
	response.Ok(app.WithData(app.ToDetail(ms.ModelToDetailDeptRes(dept))))
}
